<template>
  <el-dialog v-model="dialogVisible" title="标签设置" width="20%" :before-close="handleClose">
    <div>
      <el-input v-for="(item, i) in list" placeholder="标签名称" style="width: 100%; margin-bottom: 10px" v-model="item.name">
        <template #suffix v-if="list.length > 0">
          <IEpCircleClose style="cursor: pointer" @click="delFun(item, i)" />
        </template>
      </el-input>
      <div style="width: 100%">
        <el-button type="primary" style="width: 100%" plain @click="addList">新增</el-button>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { addLabelApi, delLabelApi } from "@/plugins/api/customer/setup/fourth";

let list = ref([{}]);

let dialogVisible = ref(false);
function handleClose(done) {
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => { });
}
let info = ref({});
function initFun(row) {
  if (row.children && row.children.length > 0) {
    list.value = row.children.map((item) => {
      return {
        name: item.name,
        id: item.id,
      };
    });
  } else {
    list.value = [{}];
  }

  info.value = Object.assign({}, row);
  dialogVisible.value = true;
}
const emit = defineEmits(["refreshList"]);
function submit() {
  if (list.value.length == 0) return ElMessage.warning("请添加标签！");
  if (
    list.value.some((item) => {
      return !item.name || item.name == "";
    })
  ) {
    return ElMessage.warning("请输入标签名称！");
  }
  let obj = {};
  // obj.name = list.value.filter(item => {
  //   return !item.id
  // }).map((ele) => {
  //   return ele.name;
  // });
  obj.name = list.value.map((ele) => {
    return ele.name;
  });
  obj.pid = info.value.id;
  addLabelApi(obj).then(() => {
    ElMessage.success("设置成功！");
    dialogVisible.value = false;
    emit("refreshList");
  });
}
function addList() {
  list.value.push({});
}
defineExpose({
  initFun,
});
function delFun(item, i) {
  if (item.id) {
    ElMessageBox.confirm("确认删除，是否继续?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        delLabelApi({
          id: item.id,
        }).then(() => {
          ElMessage({
            type: "success",
            message: "删除成功！",
          });
          list.value.splice(i, 1);
          emit("refreshList");
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消。",
        });
      });
  } else {
    list.value.splice(i, 1);
  }
}
</script>
<style scoped lang="scss"></style>
